package com.h3bpm.kumhosunny.merits.controller;


import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Notification.IDingTalkAdapter;
import OThinker.H3.Entity.Notification.Notification;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/***
 * @author zhibiao
 * @version 1.0.0
 * 部门个人绩效评估
 */

@Controller
@RequestMapping(value = "/Portal/DepartmentMyMeritsController")
public class DepartmentMyMeritsController extends ControllerBase {


    @Override
    public String getFunctionCode() {
        return null;
    }

    public static final Logger LOGGER = (Logger) LoggerFactory.getLogger(MyMeritsManagerController.class);

    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    IDingTalkAdapter iDingTalkAdapter = getEngine().getDingTalkAdapter();

    //http://localhost:8081/Portal/DepartmentMyMeritsController/startMyMeritsSonProcess?instanceId=874f9320-3e55-4462-99a6-fcb240c41754

    @RequestMapping("/startMyMeritsSonProcess")
    @ResponseBody
    public String startMyMeritsSonProcess(String instanceId) {

        String result = "200";

        try {

            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

            //数据封装
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();

            Map<String, List> resultMaps = this.myMeritsProcessiongData(instanceId, valueTable);

            for (String nowUser : resultMaps.keySet()) {
                //当前用户—子流程发起人
                User user = (User) getEngine().getOrganization().GetUnit(nowUser);
                LOGGER.info("> MeritsSon: 发起子流程 >发起人:" + user.getCode());
                BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "DepartmentOKRevalueAT", user.getCode(), false, resultMaps.get(nowUser));

                //等待1秒
                Thread.sleep(500);
                String workItemId = SqlUtil.doQuery(String.format("select  objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), user.getObjectID())).getRows().get(0).getString(0);

                String pc_url = "http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID=" + workItemId + "&time=" + System.currentTimeMillis();
                String mobile_url = "http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/" + workItemId + "?time=" + System.currentTimeMillis();

                //发送消息通知用户
                //子流程数据
                InstanceData sonData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);

                Notification notification = new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk, null, user.getObjectID(),
                        user.getDingTalkAccount(), null, 0, bpmServiceResult.getInstanceId(),
                        "" + sonData.getInstanceContext().getInstanceName(), "您有一条流程待办,点击查看", null, mobile_url, pc_url, null);

                getEngine().getNotifier().Notify(notification);

                LOGGER.info("> " + objectMapper.writeValueAsString(bpmServiceResult));
            }

        } catch (Exception e) {
            result = "500";
            e.printStackTrace();

        }

        return result;

    }


    /***
     * 数据处理返回
     * @param instanceId
     * @param valueTable
     * @return
     * @throws Exception
     */
    public Map<String, List> myMeritsProcessiongData(String instanceId, HashMap<String, Object> valueTable) throws Exception {
        Map<String, List> resultMaps = new HashMap<>();

        //获取子表数据遍历发起人
        BizObject[] meritsSonTables = (BizObject[]) valueTable.get("evaluateChartIDepartment");

        //获取团队分类
        String groupTypeStr = (String) valueTable.get("classifyIDepartment");
        //获取业务绩效
        String groupNameStr = (String) valueTable.get("PositionAndBusinessIDepartment");

        //遍历子表数据
        if (meritsSonTables.length != 0 && null != meritsSonTables) {

            for (int i = 0; i < meritsSonTables.length; i++) {
                //数据映射
                List<DataItemParam> dataParam = new ArrayList<>();

                HashMap<String, Object> objectHashMap = meritsSonTables[i].getValueTable();

                //获取当前子表评估人
                String evaluatorPerson = (String) objectHashMap.get("Assessors");
                dataParam.add(new DataItemParam("parentInstanceId", instanceId));
                dataParam.add(new DataItemParam("personal", valueTable.get("reporterIDepartment")));
                dataParam.add(new DataItemParam("performanceOfCycle", valueTable.get("peformanceOfCycleIDepartment")));
                dataParam.add(new DataItemParam("Department", groupTypeStr));
                dataParam.add(new DataItemParam("TeamName11", groupNameStr));
                dataParam.add(new DataItemParam("Assessors", evaluatorPerson));

                //日期
                dataParam.add(new DataItemParam("reportDate", valueTable.get("reportDate")));


                //放入resultMap
                resultMaps.put(evaluatorPerson, dataParam);

            }


        }


        return resultMaps;

    }


    /***
     * 子流程提交数据，返回父表
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/DepartmentMyMeritsController/sonMeritsSubmit?instanceId=89039127-a717-4d13-9684-9139939ba6b3
    @RequestMapping("/sonMeritsSubmit")
    @ResponseBody
    public String sonMeritsSubmit(String instanceId) {
        String result = "200";

        try {
            //获取当前子流程数据
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);

            //获取数据
            HashMap<String, Object> valueTable = instanceData.getBizObject().getValueTable();

            //当前子流程发起人ID
            String submitFormUserId = (String) valueTable.get("Assessors");

            //绩效等级
            String performanceRate = (String) valueTable.get("performanceRate");

            //绩效系数
            String coefficient = (String) valueTable.get("coefficient");

            //OKR(业务策略制定的深度思考)
            String okr = (String) valueTable.get("OKR");

            //业绩达成
            String KPIresults = (String) valueTable.get("KPIresults");

            //团队建设、文化与氛围
            String teamBuilding = (String) valueTable.get("teamBuilding");

            //个人学习
            String learning = (String) valueTable.get("personalLearning");

            //获取父表数据
            InstanceData parentData = new InstanceData(getEngine(), (String) valueTable.get("parentInstanceId"), User.AdministratorID);

            //封装父表数据
            HashMap<String, Object> parentValueTable = parentData.getBizObject().getValueTable();
            //获取父表下的子表数据
            BizObject[] parentSonTableValue = (BizObject[]) parentValueTable.get("evaluateChartIDepartment");

            //遍历赋值
            for (BizObject bizObject : parentSonTableValue) {
                HashMap<String, Object> objectHashMap = bizObject.getValueTable();

                //确定当前账户
                if (objectHashMap.get("Assessors").equals(submitFormUserId)) {
                    //父表赋值
                    bizObject.setItem("performanceRate", performanceRate);  //绩效等级
                    bizObject.setItem("coefficient", coefficient);  //绩效系数
                    bizObject.setItem("OKR", okr); //OKR
                    bizObject.setItem("KPIresults", KPIresults);   //业绩达成
                    bizObject.setItem("teamBuilding", teamBuilding);  //团队建设
                    bizObject.setItem("learning", learning);  //个人学习与成长
                    LOGGER.info("> MeritsSon: 子流程数据返回父表,子流程ID:" + instanceId);
                    break;
                }

            }
            //数据先录入后计算

            //遍历判断当前汇总状态
            Integer successPerson = 0;
            for (BizObject bizObject : parentSonTableValue) {
                HashMap<String, Object> objectHashMap = bizObject.getValueTable();
                //计算已完成人
                if (null != objectHashMap.get("performanceRate") && !"".equals(objectHashMap.get("performanceRate"))) {
                    successPerson++;  //已完成汇总人数+1
                }
            }

            //遍历完成判断 && 提交过来已完成人数+1
            if (successPerson != parentSonTableValue.length) {
                Integer noperson = (parentSonTableValue.length - successPerson);
                parentData.getBizObject().setItem("evaluateChartState", "未完成人数:" + noperson);
            } else {
                parentData.getBizObject().setItem("evaluateChartState", "已完成");
            }

            //保存父表所有数据
            parentData.Submit();


        } catch (Exception e) {
            result = "500";
            e.printStackTrace();
        }

        return result;
    }


}
